import axios from 'axios';
import router from '../router';
import Vue from 'vue';

const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    baseURL: Vue.prototype.$host, // 请求地址
    timeout: 50000
});

service.interceptors.request.use(
    config => {
        const token =localStorage.getItem("X-Token");  // 访问token
        if (token) {
            // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
            config.headers['X-Token'] = token
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        const res = response.data;
        if (response.status === 200) {
            if(response.data.code  === -1){
                return Promise.reject(response.data || 'error')
            }
            return response.data;
        } else {
            return Promise.reject(res.message || 'error')
        }
    },
    error => {
        console.log(error);
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject();
    }
);

export default service;
